package biz.datalk.industrialland.admin.modules.online.config.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tarofang@163.com
 * @date 2019-12-20
 */
public class FreemarkerHelper {
    private static final Logger log = LoggerFactory.getLogger(FreemarkerHelper.class);
    private static Configuration cfg;

    public FreemarkerHelper() {
    }

    static {
        cfg = new Configuration(Configuration.VERSION_2_3_28);
        // 模板对于数字超过1000，会自动格式为1,000(禁止转换)
        cfg.setNumberFormat("0.#####################");
        cfg.setClassForTemplateLoading(FreemarkerHelper.class, "/");
    }

    public static String getTemplate(String templatePath, String charset, Map<String, Object> otherParams) {
        try {
            StringWriter writer = new StringWriter();
            Template template = cfg.getTemplate(templatePath, charset);
            template.process(otherParams, writer);
            return writer.toString();
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5);
            return var5.toString();
        }
    }

    public static String getTemplate(String templatePath, Map<String, Object> otherParams) {
        return getTemplate(templatePath, StandardCharsets.UTF_8.name(), otherParams);
    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>(4);
        params.put("str", "第一个参数");
        params.put("int", 11111111);
        params.put("double", new Double("11111111112.55"));
        String str = getTemplate("/biz/datalk/framework/core/modules/online/config/engine/readTest.ftl", params);
        System.out.println(str);
    }

}
